from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from django_redis import get_redis_connection
from django.contrib.auth import login, logout, authenticate
from django.utils.decorators import method_decorator
from datetime import datetime
from django.conf import settings
import json
import re
import logging
import os

from IHome.utils.errmsg_info import error_no, error_msg
from users.models import User
from IHome.utils.mixin import login_decorator, LoginRequiredJsonMixin
from IHome.libs.qiniuyun.qiniu_storage import storage

# Create your views here.

# 创建日志生成器
logger = logging.getLogger('django')


class AuthUserView(LoginRequiredJsonMixin, View):
    """用户认证
    api/v1.0/user/auth
    """
    def post(self, request):
        json_dict = json.loads(request.body.decode())
        real_name = json_dict.get('real_name')
        id_card = json_dict.get('id_card')

        if not all([real_name, id_card]):
            return JsonResponse({'errno': error_no['DATAERR'],
                                 'errmsg': error_msg['DATAERR']})
        if not re.match(r'^[\u4e00-\u9fa5]{2,4}$', real_name):
            return JsonResponse({'errno': error_no['DATAERR'],
                                 'errmsg': 'real_name格式不对'})
        if not re.match(r'^[1-9]\d{5}(18|19|20|(3\d))\d{2}'
                        r'((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)'
                        r'\d{3}[0-9Xx]$', id_card):

            return JsonResponse({'errno': error_no['DATAERR'],
                                 'errmsg': 'id_card格式不对'})

        user = request.user
        # 判断用户是否认证
        if user.real_name == real_name or user.id_card == id_card:
            return JsonResponse({'errno': error_no['DATAEXIST'],
                                 'errmsg': '用户已认证'})
        try:
            user.real_name = real_name
            user.id_card = id_card
            user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': error_no['DBERR'],
                                 'errmsg': error_msg['DBERR']})

        return JsonResponse({'errno': error_no['OK'],
                             'errmsg': '用户认证成功'})

    def get(self, request):
        data = {
            'real_name': request.user.real_name,
            'id_card': request.user.id_card
        }

        # if not all([request.user.real_name, request.user.id_card]):
        #     return JsonResponse({'errno': 400,
        #                          'errmsg': '未认证',
        #                          'data': data})

        return JsonResponse({'errno': error_no['OK'],
                             'errmsg': '用户已认证',
                             'data': data})


class UploadAvatarView(LoginRequiredJsonMixin, View):
    """上传个人头像
    api/v1.0/user/avatar
    """
    def post(self, request):
        file_path = request.FILES.get('avatar')
        if not file_path:
            return JsonResponse({'errno': error_no['DATAERR'],
                                 'errmsg': error_msg['DATAERR']})

        # print('file_path: ', file_path)   ----> 1.jpg
        key = storage(file_path.read())

        # print('key类型: ', type(key))   ----->  <class 'str'>

        request.user.avatar = key
        request.user.save()

        response = JsonResponse({'errno': error_no['OK'],
                                 'errmsg': error_msg['OK'],
                                'avatar_url': settings.QINIU_URL + key
                                 })

        response.set_cookie('name', request.user.username)

        return response


class ModifyNameView(LoginRequiredJsonMixin, View):
    """修改用户名
    api/v1.0/user/name
    """
    def put(self, request):
        json_dict = json.loads(request.body.decode())
        name = json_dict.get('name')
        if not name:
            return JsonResponse({'errno': error_no['DATAERR'], 'errmsg': error_msg['DATAERR']})
        if not re.match(r'^[a-zA-Z_-]{5,20}$', name):
            return JsonResponse({'errno': error_no['DATAERR'], 'errmsg': error_msg['DATAERR']})
        if name == request.user.username:
            return JsonResponse({'errno': error_no['DATAERR'], 'errmsg': '重名了'})

        request.user.username = name
        request.user.save()

        return JsonResponse({'errno': error_no['OK'], 'errmsg': '用户名修改成功'})


class UserInfoView(LoginRequiredJsonMixin, View):
    """用户个人信息
    api/v1.0/user
    """
    def get(self, request):
        """strftime 把时间转换成字符串"""
        user = request.user
        date_joined = datetime.strptime(user.date_joined.strftime("%Y-%m-%d %H:%M:%S"), "%Y-%m-%d %H:%M:%S")

        # print(type(user.date_joined))-----> <class 'datetime.datetime'>
        # print(date_joined)  ----> 2020-07-07 08:41:14

        data = {
            'avatar_url': settings.QINIU_URL + str(user.avatar),
            'create_time': date_joined,
            'mobile': user.mobile,
            'name': user.username,
            'user_id': user.id
        }

        return JsonResponse({
            'errno': error_no['OK'],
            'errmsg': error_msg['OK'],
            'data': data
        })


class RegisterView(View):
    """注册接口
    /api/v1.0/users
    """
    def post(self, request):
        # 1.接收参数
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        phonecode = json_dict.get('phonecode')
        password = json_dict.get('password')

        # 2.校验整体
        if not all([mobile, phonecode, password]):
            return JsonResponse({
                'errno': error_no['DATAERR'],
                'errmsg': error_msg['DATAERR']
            })
        # 3.手机号校验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({
                'errno': error_no['DATAERR'],
                'errmsg': error_msg['DATAERR']
            })
        # 4.密码校验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({
                'errno': error_no['PWDERR'],
                'errmsg': error_msg['PWDERR']
            })

        # 6.短信验证码校验
        conn = get_redis_connection('verify_code')
        code_from_redis = conn.get('sms_%s' % mobile)

        # 7.短信验证码是否过期
        if not code_from_redis:
            return JsonResponse({
                'errno': error_no['DATAERR'],
                'errmsg': error_msg['DATAERR']
            })

        if phonecode != code_from_redis.decode():
            return JsonResponse({
                'errno': error_no['DATAERR'],
                'errmsg': error_msg['DATAERR']
            })

        # local_path = settings.BASE_DIR + '/libs/qiniuyun/1.png'
        # fp = open(local_path)
        # data = fp.read()
        # key = storage(data)
        # key = 'FjsU0fOyLyy41jphLWnr2fFgidcl'
        # print(type(key))

        # avatar = settings.QINIU_URL + key
        avatar = settings.USER_AVATAR_KEY

        user = User.objects.create_user(
            username=mobile,
            password=password,
            mobile=mobile,
            avatar=avatar
        )

        login(request, user)

        response = JsonResponse({
            'errno': error_no['OK'],
            'errmsg': error_msg['OK']
        })

        response.set_cookie('name', user.username)

        # 8.返回
        return response


class LoginLogoutView(View):
    """/api/v1.0/session"""
    def post(self, request):
        """ 登录接口"""
        # 1.接收参数
        json_dict = json.loads(request.body.decode())
        account = json_dict.get('mobile')
        password = json_dict.get('password')

        # 2.校验参数
        if not all([account, password]):
            return JsonResponse({
                'errno': error_no['DATAERR'],
                'errmsg': error_msg['DATAERR']
            })

        if not re.match(r'^[a-zA-Z0-9_-]{8,20}$', password):
            return JsonResponse({
                'errno': error_no['DATAERR'],
                'errmsg': error_msg['DATAERR']
            })

        if re.match(r'^1[3-9]\d{9}$', account):
            # 把username字段换成赋值的字段
            User.USERNAME_FIELD = 'mobile'

        else:
            User.USERNAME_FIELD = 'username'

        # 只是认证输入的用户是否是美多用户,返回一个对象
        user = authenticate(username=account, password=password)

        if user is None:
            return JsonResponse({
                'errno': error_no['LOGINERR'],
                'errmsg': error_msg['LOGINERR']
            })

        # 4.状态保持
        login(request, user)

        response = JsonResponse({
            'errno': error_no['OK'],
            'errmsg': error_msg['OK']
        })
        response.set_cookie('name', user.username)
        # 5.返回json
        return response

    @method_decorator(login_decorator)
    def get(self, request):
        """判断是否登录"""
        name = request.user.username

        return JsonResponse({
            'errno': error_no['OK'],
            'errmsg': '已登录',
            'data': {'name': name, 'user_id': request.user.id}
        })

    @method_decorator(login_decorator)
    def delete(self, request):
        logout(request)
        response = JsonResponse({'errno': error_no['OK'], 'errmsg': '已登出'})
        response.delete_cookie('name')
        return response


